package com.jgy.juc.chatgpt;

import org.junit.Test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MultiThreadDemo {
    private static ExecutorService executorService;

    public MultiThreadDemo(int threads) {
        // 创建一个线程池，线程数量为传入的参数
        executorService = Executors.newFixedThreadPool(threads);
    }

    public static void start() {
        for (int i = 0; i < 10; i++) {
            // 提交一个任务到线程池
            executorService.submit(new Worker(i));
        }
        // 关闭线程池
        executorService.shutdown();
    }

    public static void main(String[] args) {
       MultiThreadDemo multiThreadDemo = new MultiThreadDemo(2);

       MultiThreadDemo.start();
    }





    private static class Worker implements Runnable {
        private int id;

        public Worker(int id) {
            this.id = id;
        }

        @Override
        public void run() {
            System.out.println("Worker " + id + " started.");
            try {
                // 模拟一个耗时的任务
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Worker " + id + " finished.");
        }
    }

}
